#include <pthread.h>
#include "sleep.h"
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <malloc.h>
#include "io.h"
#include "cpu.h"


void * ioDeviceThreadAction(IODevice);
void * keyboardThreadAction(IODevice);

IODevice initializeIODevice(void (*func_ptr), enum DeviceType type, CPU_IO cpu) {
	IODevice io = (IODevice) malloc(sizeof(IOStr));
	io->type = type;
	io->function_ptr = func_ptr;
	io->cpu = cpu;
	return io;
}

void startIODevice(IODevice io) {

	switch (io->type) {
		case IO:
			pthread_create(&io->thread, NULL, ioDeviceThreadAction, io);
			break;
		case KEYBOARD:
			pthread_create(&io->thread, NULL, keyboardThreadAction, io);
			break;
	}
	return;
}

void * keyboardThreadAction(IODevice io) {
	void * ret;
	int c;
	do {
		c = getchar();
	} while (c == EOF || c == '\n' || c == '\r');
	(io->function_ptr)(io->cpu);
	return ret;
}

void * ioDeviceThreadAction(IODevice io) {
	time_t dummy;
	void * ret;

	srand((unsigned int) time(&dummy));
	milliSleep((rand() % MAX_WAIT) + 2);
	(io->function_ptr)(io->cpu);
	return ret;
}
